package com.example.finaly;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity  {
    Button stop;
    TextView tv;
    File soundFile;
    MediaRecorder mediaRecorder;
    MediaPlayer mediaPlayer;
    Toast toast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=findViewById(R.id.tv);//显示当前录音状态
        stop=(Button)findViewById(R.id.stop);//停止录音
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//点击到按钮
                if(soundFile!=null&&soundFile.exists()){
                    tv.setText("录音已保存");
                    mediaRecorder.stop();//录音停止
                    mediaRecorder.release();//录音释放
                    mediaRecorder=null;
                }
            }
        });
        SensorManagerHelper sensorHelper=new SensorManagerHelper(this);
        sensorHelper.setOnShakeListener(new SensorManagerHelper.OnShakeListener() {
            @Override
            public void onShake() {//监听到摇晃
                try{
                    tv.setText("正在录音");

                    soundFile=new File(Environment.getExternalStorageDirectory().getCanonicalFile()+"/s.amr");//新建录音文件
                    mediaRecorder=new MediaRecorder();
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置声音来源
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置录制的声音的输出格式
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置声音编码模式
                    mediaRecorder.setOutputFile(soundFile.getAbsolutePath());//声音保存路径
                    mediaRecorder.prepare();
                    mediaRecorder.start();//开始录音


                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if(soundFile!=null&&soundFile.exists()){
            mediaRecorder.stop();;
            mediaRecorder.release();
            mediaRecorder=null;
        }
        super.onDestroy();
    }
}
